<template>
    <div style="width: 100%">
        <el-form :disabled="dialogType==='view'"
                 ref="form"
                 size="small"
                 :model="formData"
                 :rules="rules"
                 label-width="100px">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="编码标识" prop="name">
                        <el-input v-model="formData.name"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="中文名称" prop="nameCn">
                        <el-input v-model="formData.nameCn"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="属性类型" prop="attributeType">
                        <el-select style="width:100%" v-model="formData.attributeType">
                            <el-option label="字符串" value="string"></el-option>
                            <el-option label="数字" value="number"></el-option>
                            <!--                            <el-option label="日期" value="date"></el-option>-->
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="英文名称">
                        <el-input v-model="formData.nameEn"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="枚举分类" prop="codeClassify">
                        <el-select style="width:100%" v-model="formData.codeClassify">
                            <template v-for="item in enumTypeList">
                                <el-option :label="item.code" :value="item.value"></el-option>
                            </template>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="英文描述">
                        <el-input v-model="formData.describeEn"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="中文描述">
                        <el-input v-model="formData.describeCn"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div>
            <avue-crud :option="{...option,selection:dialogType!=='view'}"
                       :table-loading="loading"
                       :data="formData.codeList"
                       @selection-change="selectionChange"
                       ref="crud">
                <template slot="menuLeft">
                    <el-button size="small" type="primary" :disabled="dialogType==='view'" @click="addLine">添加行
                    </el-button>
                    <el-button size="small" type="danger" :disabled="dialogType==='view'||selection.length===0"
                               @click="remove">
                        移除
                    </el-button>
                </template>

                <template slot="isDefault" slot-scope="{row}">
                    <el-radio :disabled="dialogType==='view'"
                              :value="row.isDefault"
                              :label="1"
                              @change="changeRadio(row)">
                        &nbsp;
                    </el-radio>
                </template>
            </avue-crud>
        </div>
        <div class="md-component-btns">
            <el-button size="medium" v-if="dialogType==='view'" type="primary"
                       @click="()=>{$emit('viewToEdit'),viewToEdit()}">编辑
            </el-button>
            <el-button size="medium" v-if="dialogType!=='view'" type="primary" @click="save">保存</el-button>
            <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
        </div>
    </div>
</template>

<script>
import * as api from "@/api/modulManage/enum"
import {getEnumType} from "@/api/common";

export default {
    name: "enumManageTemp",
    data() {
        return {
            formData: {
                "name": "",
                "nameEn": "",
                "attributeType": "",
                "describeEn": "",
                "describeCn": "",
                codeList: []
            },
            rules: {
                name: [{
                    required: true,
                    message: "请输入编码",
                    trigger: "blur"
                }, {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确编码标识'}],
                nameCn: [{required: true, message: "请输入中文名称", trigger: "blur"}],
                attributeType: [{required: true, message: "请选择属性类型", trigger: "change"}],
                nameEn: [{required: true, message: "请输入英文名称", trigger: "blur"}],
                codeClassify: [{required: true, message: "请选择枚举分类", trigger: "change"}],
            },

            loading: false,
            option: {
                height: 'auto',
                calcHeight: 30,
                dialogWidth: 900,
                tip: false,
                searchShow: true,
                searchMenuSpan: 6,
                border: true,
                index: true,
                selection: true,
                labelWidth: 120,
                menuWidth: 90,
                viewBtn: false,
                dialogClickModal: false,
                tabs: true,
                delBtn: false,
                addBtn: false,
                editBtn: false,
                refreshBtn: false,
                columnBtn: false,
                align: "center",
                menu: false,
                column: [
                    {
                        label: "实际值",
                        prop: "value",
                        cell: true,
                        rules: [
                            {required: true, message: '请输入实际值', trigger: 'blur'},
                            {pattern: '^[\\w\\-: ]+$', message: '请输入数字/字母/下划线'}
                        ]
                    },
                    {
                        label: '显示值',
                        prop: 'name',
                        cell: true,
                        rules: [
                            {required: true, message: '请输入显示值', trigger: 'blur'}
                        ]
                    },
                    {
                        label: "是否默认值",
                        prop: "isDefault",
                        width: "100px",
                        /*  type: "select",
                          dicData: [
                            {label: "是", value: 1},
                            {label: "否", value: 0},
                          ],*/
                        slot: true,
                        // cell: true,
                    },
                    {
                        label: "描述",
                        prop: "describeCn",
                        cell: true,
                    }
                ]
            },
            selection: [],

            enumTypeList: [],

            dialogType: "add"
        }
    },
    methods: {
        changeRadio(row) {
            let data = this.deepCopy(this.formData.codeList);
            this.formData.codeList = [];
            data.forEach(i => {
                if (i.ID === row.ID) {
                    i.isDefault = 1;
                } else {
                    i.isDefault = 0;
                }
            })
            this.formData.codeList = data;
        },
        save() {
            this.$refs["form"].validate(async f => {
                if (f) {
                    let method = this.dialogType === "add" ? 'addEnum' : 'updateEnum';
                    let data = this.deepCopy(this.formData.codeList);
                    let dataName = [];
                    //当下方列表不为空时，是否默认值必须有值
                    if (data.length > 0) {
                        let isDefault = false;
                        for (let i = 0; i < data.length; i++) {
                            let item = data[i];
                            if (item.isDefault) {
                                // 当已经查到存在默认值时，退出循环
                                isDefault = item.isDefault;
                                break;
                            }
                        }
                        if (!isDefault) {
                            this.$message.warning("请选择是否默认值");
                            return;
                        }

                        let hasVal = true;
                        let hasNum = 0;

                        data.forEach(item => {
                            if (item.name) {
                                hasNum++;
                            }
                            if (item.value) {
                                hasNum++;
                            }
                            if (!dataName.includes(item.value)) {
                                dataName.push(item.value)
                            }
                        })

                        if (hasNum !== data.length * 2) {
                            hasVal = false
                        }

                        if (!hasVal) {
                            this.$message.warning("请填写实际/显示值");
                            return;
                        }

                        let res = await this.$refs["crud"].validateCellForm()
                        if (Object.keys(res).length > 0) {
                            this.$message.warning("请输入正确的实际值");
                            return;
                        }

                        if (dataName.length !== data.length) {
                            this.$message.warning("实际值重复");
                            return;
                        }
                    } else {
                        this.$message.warning("枚举值列表不能为空");
                        return;
                    }

                    api[method]({...this.formData}).then(() => {
                        this.$message.success("保存成功");
                        this.$emit('removeThisTabs');
                        this.$emit("refresh");
                    })
                }
            })
        },
        selectionChange(v) {
            this.selection = v;
        },
        addLine() {
            this.formData.codeList.push({
                name: "",
                value: "",
                isDefault: "",
                describeCn: "",
                $cellEdit: true,
                ID: this.getOnlyId()
            })
        },
        remove() {
            let data = this.deepCopy(this.formData.codeList);
            let index = this.selection.map(i => i.$index);

            this.formData.codeList = [];
            data.forEach(i => {
                if (!index.includes(i.$index)) {
                    this.formData.codeList.push(i)
                }
            })
        },
        // 打开
        open() {
            this.resetDialog();
            this.visible = true;
            this.dialogType = "add";
        },
        // 关闭
        close() {
            this.visible = false;
        },
        viewToEdit() {
            this.dialogType = "edit";
            let data = this.deepCopy(this.formData.codeList);
            data.forEach(item => {
                item.$cellEdit = true;
                item.ID= this.getOnlyId()
            })
            this.$set(this.formData, "codeList", data);
        },
        // 查看
        view(row) {
            api.getEnumDetails({oid: row.oid}).then(res => {
                const {data} = res.data;
                this.formData = {...data};
                this.visible = true;
                this.dialogType = "view";
            })
        },
        // 编辑
        edit(row) {
            this.resetDialog();
            api.getEnumDetails({oid: row.oid}).then(res => {
                const {data} = res.data;
                data.codeList.forEach(item => {
                    item.$cellEdit = true;
                    item.ID= this.getOnlyId()
                })
                this.formData = {...data};
                this.visible = true;
                this.dialogType = "edit";
            })
        },
        resetDialog() {
            this.formData = {
                "name": "",
                "nameEn": "",
                "attributeType": "",
                "describeEn": "",
                "describeCn": "",
                codeList: []
            }
        }
    },
    mounted() {
        getEnumType().then(res => {
            this.enumTypeList = res.data.data;
        })
    }
}
</script>

<style scoped>

</style>
